import { FC, useEffect, useRef, useState } from "react"
import Taro, { useRouter } from '@tarojs/taro'
import { tagListObj, GoodsInfo } from './hook/usePageEffect'
import { Button, Picker } from "@tarojs/components"
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"
import map from '@/resource/map.png'
import TagListPick from '../TagListPick'
import uncheck from '../../resource/uncheck.png'
import checked from '../../resource/checked.png'
import style from './style.less'

const Edit: FC = () => {
  const router = useRouter()
  const param = useRef(JSON.parse(router.params.param as string))
  const orderNumber = router.params.orderNumber
  console.log('编辑', param, orderNumber);

  const goodsInfo = useRef<GoodsInfo>({
    loadLinkman: param.current.loadLinkman,
    loadTime: param.current.loadTime,
    truckType: param.current.truckType,
    cargoId: param.current.cargoId,
    cargoFee: param.current.cargoFee,
    loadAddress: param.current.loadAddress,
    truckWeight: param.current.truckWeight,
    remark: param.current.remark,
    unloadingAdress: param.current.unloadingAdress,
    unloadingLinkman: param.current.unloadingLinkman,
    packingType: param.current.packingType,
    cargoCapacipy: param.current.cargoCapacipy,
    unloadingTime: param.current.unloadingTime,
    deposit: param.current.deposit,
    truckLength: param.current.truckLength,
    needReturnDeposit: param.current.needReturnDeposit,
    cargoName: param.current.cargoName,
    loadLatitude: param.current.loadLatitude,
    loadLongitude: param.current.loadLongitude,
    unloadLatitude: param.current.unloadLatitude,
    unloadLongitude: param.current.unloadLongitude,
    estimateDistance: param.current.estimateDistance,
    standardCargo: param.current.standardCargo
  })

  useEffect(() => {
    goodsInfo.current.loadLatitude = param.current.loadLatitude
    goodsInfo.current.loadLongitude = param.current.loadLongitude
    goodsInfo.current.unloadLatitude = param.current.unloadLatitude
    goodsInfo.current.unloadLongitude = param.current.unloadLongitude
    source.current!.value = param.current.loadAddress.split(' ')[0]
    source2.current!.value = param.current.loadAddress.split(' ')[1]
    target.current!.value = param.current.unloadingAdress.split(' ')[0]
    target2.current!.value = param.current.unloadingAdress.split(' ')[1]
    info.current!.value = param.current.cargoName + ' ' + param.current.packingType
    weight.current!.value = param.current.truckWeight
    volume.current!.value = param.current.cargoCapacipy
    info2.current!.value = param.current.truckWeight + '吨 ' + param.current.cargoCapacipy + '立方米'
    car.current!.value = param.current.truckLength + '米 ' + param.current.truckType
    date.current!.value = param.current.loadTime.split(' ')[0]
    time.current!.value = param.current.loadTime.split(' ')[1]
    date2.current!.value = param.current.unloadingTime.split(' ')[0]
    time2.current!.value = param.current.unloadingTime.split(' ')[1]
    deposit.current!.value = param.current.deposit
    freight.current!.value = param.current.cargoFee
    setSelect(param.current.needReturnDeposit)
    loadingContactor.current!.value = param.current.loadLinkman
    unloadingContactor.current!.value = param.current.unloadingLinkman
    remark.current!.value = param.current.remark
  }, [])

  const [carLength, setCarLength] = useState('')
  const [carType, setCarType] = useState('')
  const [tagListPickVisible, setTagListPickVisible] = useState(false)
  const [isShow, setIsShow] = useState(false)
  const source = useRef<HTMLInputElement>(null)
  const source2 = useRef<HTMLInputElement>(null)
  const target = useRef<HTMLInputElement>(null)
  const target2 = useRef<HTMLInputElement>(null)
  const info = useRef<HTMLInputElement>(null)
  const info2 = useRef<HTMLInputElement>(null)
  const weight = useRef<HTMLInputElement>(null)
  const volume = useRef<HTMLInputElement>(null)
  const car = useRef<HTMLInputElement>(null)
  const date = useRef<HTMLInputElement>(null)
  const time = useRef<HTMLInputElement>(null)
  const date2 = useRef<HTMLInputElement>(null)
  const time2 = useRef<HTMLInputElement>(null)

  // const [multiArray, setMultiArray] = useState<string[][]>([['金属钢材', '鲜活水产', '煤炭矿产', '瓜果蔬菜', '木头材料'], ['钢管金属管', '铝制材料', '角钢槽钢', '金属工业原料'], ['裸装', '木箱', '托盘', '捆扎', '架子', '其他']])
  // const [multiIndex, setMultiIndex] = useState<number[]>([0, 0, 0])

  const [check, setCheck] = useState(false)
  const [select, setSelect] = useState(0)
  const deposit = useRef<HTMLInputElement>(null)
  const freight = useRef<HTMLInputElement>(null)
  const loadingContactor = useRef<HTMLInputElement>(null)
  const unloadingContactor = useRef<HTMLInputElement>(null)
  const remark = useRef<HTMLTextAreaElement>(null)

  const getDate = () => {
    var time = new Date();
    var year = time.getFullYear()  //年
    var month = ("0" + (time.getMonth() + 1)).slice(-2); //月
    var day = ("0" + time.getDate()).slice(-2); //日
    var mydate = year + "-" + month + "-" + day;
    return mydate
  }

  const choosePosition = (num) => {
    Taro.chooseLocation({
      success: (res) => {
        console.log(res);
        if (num === 1) {
          source2.current!.value = res.name
          goodsInfo.current.loadLatitude = res.latitude
          goodsInfo.current.loadLongitude = res.longitude
          return
        }
        if (num === 2) {
          target2.current!.value = res.name
          goodsInfo.current.unloadLatitude = res.latitude
          goodsInfo.current.unloadLongitude = res.longitude
          return
        }
      },
      fail: (err) => {
        console.log(err);
      }
    })
  }

  const handleTagListPickConfirm = (pickedTags: arrObject) => {
    let [carLenthPicked, carTypesPicked] = [
      pickedTags['车长'],
      pickedTags['车型'],
    ];

    if (carLenthPicked[0] && carTypesPicked[0]) {
      setTagListPickVisible(false)
      car.current!.value = carLenthPicked[0] + '米 ' + carTypesPicked[0]
      goodsInfo.current.truckLength = carLenthPicked[0]
      goodsInfo.current.truckType = carTypesPicked[0]
    } else {
      Taro.showToast({
        title: '请选择',
        icon: 'none',
        duration: 1500
      })
    }

    carLenthPicked.length && setCarLength(`车长: ${carLenthPicked[0]}`)
    carTypesPicked.length && setCarType(`车型: ${carTypesPicked[0]}`)
  }

  const changeRegion = (e, num) => {
    if (num === 0) {
      source.current!.value = e.detail.value[0] + '-' + e.detail.value[1] + '-' + e.detail.value[2]
    } else if (num === 1) {
      target.current!.value = e.detail.value[0] + '-' + e.detail.value[1] + '-' + e.detail.value[2]
    } else if (num === 2) {
      date.current!.value = e.detail.value
    } else if (num === 3) {
      time.current!.value = e.detail.value
    } else if (num === 4) {
      date2.current!.value = e.detail.value
    } else if (num === 5) {
      time2.current!.value = e.detail.value
    }
  }

  // const bindMultiPickerChange = (e) => {
  //   info.current!.value = multiArray[1][e.detail.value[1]] + multiArray[2][e.detail.value[2]]
  //   goodsInfo.current.cargoName = multiArray[1][e.detail.value[1]]
  //   goodsInfo.current.packingType = multiArray[2][e.detail.value[2]]
  // }

  // const bindMultiPickerColumnChange = (e) => {
  //   console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
  //   var data = {
  //     // multiArray: [[...multiArray[0]], [...multiArray[1]]],
  //     multiArray: [...multiArray],
  //     multiIndex: [...multiIndex]
  //   };
  //   data.multiIndex[e.detail.column] = e.detail.value;
  //   switch (e.detail.column) {
  //     case 0:
  //       // ['金属钢材', '鲜活水产', '煤炭矿产']
  //       switch (data.multiIndex[0]) {
  //         case 0:
  //           data.multiArray[1] = ['钢管金属管', '铝制材料', '角钢槽钢', '金属工业原料'];
  //           data.multiArray[2] = ['裸装', '木箱', '托盘', '捆扎', '架子', '其他'];
  //           break;
  //         case 1:
  //           data.multiArray[1] = ['活鱼', '活虾', '活蟹', '海鲜海产品'];
  //           data.multiArray[2] = ['水箱', '其他'];
  //           break;
  //         case 2:
  //           data.multiArray[1] = ['矿粉矿渣', '煤炭'];
  //           data.multiArray[2] = ['吨包', '袋装', '托盘', '散装', '其他'];
  //           break;
  //         case 3:
  //           data.multiArray[1] = ['叶菜', '根菜', '葱蒜', '薯芋', '瓜类', '豆类', '新鲜菌菇'];
  //           data.multiArray[2] = ['袋装', '筐装', '散装', '纸箱', '其他'];
  //           break;
  //         case 4:
  //           data.multiArray[1] = ['花草', '木材', '木方方料', '木板'];
  //           data.multiArray[2] = ['裸装', '捆扎', '散装', '袋装', '其他'];
  //           break;
  //       }
  //       data.multiIndex[1] = 0;
  //       data.multiIndex[2] = 0;
  //       break;
  //     case 1:
  //       switch (data.multiIndex[0]) {
  //         case 0:
  //           switch (data.multiIndex[1]) {
  //             case 0:
  //               data.multiArray[2] = ['裸装', '木箱', '托盘', '捆扎', '架子', '其他'];
  //               break;
  //             case 1:
  //               data.multiArray[2] = ['裸装', '木箱', '托盘', '压块', '架子', '其他'];
  //               break;
  //             case 2:
  //               data.multiArray[2] = ['裸装', '托盘', '捆扎', '其他'];
  //               break;
  //             case 3:
  //               data.multiArray[2] = ['吨包', '袋装', '托盘', '木箱', '桶装', '其他'];
  //               break;
  //           }
  //           break;
  //         case 1:
  //           switch (data.multiIndex[1]) {
  //             case 0:
  //               data.multiArray[2] = ['水箱', '其他'];
  //               break;
  //             case 1:
  //               data.multiArray[2] = ['泡沫箱', '水箱', '其他'];
  //               break;
  //             case 2:
  //               data.multiArray[2] = ['泡沫箱', '其他'];
  //               break;
  //             case 3:
  //               data.multiArray[2] = ['水箱', '袋装', '其他'];
  //               break;
  //           }
  //           break;
  //         case 2:
  //           switch (data.multiIndex[1]) {
  //             case 0:
  //               data.multiArray[2] = ['吨装', '袋装', '托盘', '散装', '其他'];
  //               break;
  //             case 1:
  //               data.multiArray[2] = ['吨装', '袋装', '托盘', '散装', '其他'];
  //               break;
  //           }
  //           break;
  //         case 3:
  //           switch (data.multiIndex[1]) {
  //             case 0:
  //               data.multiArray[2] = ['袋装', '筐装', '散装', '纸箱', '其他'];
  //               break;
  //             case 1:
  //               data.multiArray[2] = ['散装', '筐装', '袋装', '纸箱', '其他'];
  //               break;
  //             case 2:
  //               data.multiArray[2] = ['袋装', '纸箱', '散装', '筐装', '其他'];
  //               break;
  //             case 3:
  //               data.multiArray[2] = ['纸箱', '筐装', '散装', '袋装', '其他'];
  //               break;
  //             case 4:
  //               data.multiArray[2] = ['袋装', '散装', '筐装', '纸箱', '其他'];
  //               break;
  //             case 5:
  //               data.multiArray[2] = ['筐装', '袋装', '散装', '纸箱', '其他'];
  //               break;
  //             case 6:
  //               data.multiArray[2] = ['袋装', '筐装', '纸箱', '散装', '其他'];
  //               break;
  //           }
  //           break;
  //         case 4:
  //           switch (data.multiIndex[1]) {
  //             case 0:
  //               data.multiArray[2] = ['裸装', '捆扎', '散装', '袋装', '其他'];
  //               break;
  //             case 1:
  //               data.multiArray[2] = ['散装', '木箱', '裸装', '袋装', '其他'];
  //               break;
  //             case 2:
  //               data.multiArray[2] = ['裸装', '捆扎', '散装', '袋装', '其他'];
  //               break;
  //             case 3:
  //               data.multiArray[2] = ['袋装', '捆扎', '散装', '裸装', '其他'];
  //               break;
  //           }
  //           break;
  //       }
  //       data.multiIndex[2] = 0;
  //       console.log(data.multiIndex);
  //       break;
  //   }
  //   console.log(data.multiArray, data.multiIndex);
  //   setMultiArray(data.multiArray)
  //   setMultiIndex(data.multiIndex)
  // }

  const showInfo = () => {
    if (weight.current?.value && volume.current?.value) {
      info2.current!.value = ` ${weight.current.value}吨 ${volume.current.value}立方米`
      goodsInfo.current.truckWeight = Number(weight.current.value)
      goodsInfo.current.cargoCapacipy = Number(volume.current.value)
      setIsShow(false)
    } else {
      Taro.showToast({
        title: '请填写',
        icon: 'none',
        duration: 1500
      })
    }
  }

  const estimate = () => {
    Taro.showLoading({ title: '估价中' })
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-cargo/publish/getPrePrice',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token'),
        cargoWeight: weight.current!.value,
        cargoCapacity: volume.current!.value,
        secondCategory: goodsInfo.current.cargoName,
        loadHhour: goodsInfo.current.loadTime,
        truckType: goodsInfo.current.truckType,
        truckLength: goodsInfo.current.truckLength,
        startLon: goodsInfo.current.loadLongitude,
        startLat: goodsInfo.current.loadLatitude,
        endLon: goodsInfo.current.unloadLongitude,
        endLat: goodsInfo.current.unloadLatitude,
      }),
      success: (data) => {
        console.log('预估运费', data);
        if (isNaN(data.data.price)) {
          freight.current!.value = '1437'
        } else {
          freight.current!.value = String(data.data.price)
        }
        Taro.hideLoading()
        // Taro.atMessage({
        //   message: '已为您预估此单运费供您参考',
        //   type: 'success',
        //   duration: 300000
        // })
      },
      fail: () => {
        console.log('预估运费失败');
        Taro.hideLoading()
      }
    })
  }

  const submit = () => {
    if (!check) {
      Taro.showToast({
        title: '请勾选同意协议',
        icon: 'none',
        duration: 1500
      })
      return
    }
    if (source2.current?.value && target2.current?.value &&
      deposit.current?.value && freight.current?.value &&
      loadingContactor.current?.value && unloadingContactor.current?.value) {
      goodsInfo.current.loadAddress = source.current!.value + ' ' + source2.current!.value
      goodsInfo.current.unloadingAdress = target.current!.value + ' ' + target2.current!.value
      goodsInfo.current.deposit = Number(deposit.current.value)
      goodsInfo.current.cargoFee = Number(freight.current.value)
      goodsInfo.current.loadLinkman = loadingContactor.current.value
      goodsInfo.current.unloadingLinkman = unloadingContactor.current.value
      goodsInfo.current.remark = remark.current?.value as string
      goodsInfo.current.needReturnDeposit = select
      goodsInfo.current.loadTime = date.current!.value + ' ' + time.current!.value
      goodsInfo.current.unloadingTime = date2.current!.value + ' ' + time2.current!.value

      console.log('编辑参数', goodsInfo.current);


      Taro.showLoading({ title: '变更处理中' })
      Taro.request({
        url: 'http://10.190.84.29:9527/fta-cargo/blackboard/editCargo',
        method: 'POST',
        data: JSON.stringify({
          ...goodsInfo.current,
          orderNumber: orderNumber,
          openId: Taro.getStorageSync('token'),
          shipperIdNo: param.current.shipperIdNo
        }),
        success: (data) => {
          console.log('运单变更', data);

          if (data.data.data.result) {
            Taro.hideLoading()
            Taro.reLaunch({ url: '/packageA/success/index?title=发货变更&info=重发货源成功～' })
          } else {
            Taro.showToast({
              title: '变更失败',
              icon: 'none',
              duration: 1500
            })
          }
        },
        fail: () => {
          Taro.hideLoading()
        }
      })
    }
  }

  return (
    <div className={style.root}>
      <div className="address">
        <div className="zhuang" >装</div>
        <Picker mode='region' value={['江苏省', '南京市', '雨花台区']} onChange={(e) => { changeRegion(e, 0) }}>
          <input ref={source} type="text" placeholder="省、市、区" disabled className="input" />
        </Picker>
        <div className="position" onClick={() => { choosePosition(1) }}>
          <input ref={source2} type="text" disabled placeholder="请选择具体装货地址" />
          <img src={map} alt="" />
        </div>
        <div className="line" />
        <div className="xie">卸</div>
        <Picker mode='region' value={['北京市', '北京市', '朝阳区']} onChange={(e) => { changeRegion(e, 1) }}>
          <input ref={target} type="text" placeholder="省、市、区" disabled className="input" />
        </Picker>
        <div className="position" onClick={() => { choosePosition(2) }}>
          <input ref={target2} type="text" disabled placeholder="请选择具体卸货地址" />
          <img src={map} alt="" />
        </div>
      </div>
      {/* <Picker mode='multiSelector' range={multiArray} value={multiIndex} onChange={bindMultiPickerChange} onColumnChange={bindMultiPickerColumnChange}> */}
      <div className="info">
        <div>货物信息:</div>
        <input ref={info} type="text" placeholder=">" disabled className="grey" />
      </div>
      {/* </Picker> */}
      {/* <div className="info" onClick={() => { setIsShow(true) }}> */}
      <div className="info">
        <div>重量体积:</div>
        <input ref={info2} type="text" placeholder=">" disabled className="grey" />
      </div>
      {/* <div className="info" onClick={() => { setTagListPickVisible(true) }}> */}
      <div className="info">
        <div>车长车型:</div>
        <input ref={car} type="text" placeholder=">" disabled className="grey" />
      </div>
      <Picker mode='date' value="" start={getDate()} onChange={(e) => { changeRegion(e, 2) }}>
        <div className="info">
          <div>装货日期:</div>
          <input ref={date} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <Picker mode='time' value="12:01" onChange={(e) => { changeRegion(e, 3) }}>
        <div className="info">
          <div>装货时间:</div>
          <input ref={time} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <Picker mode='date' value="" start={getDate()} onChange={(e) => { changeRegion(e, 4) }}>
        <div className="info">
          <div>卸货日期:</div>
          <input ref={date2} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <Picker mode='time' value="12:01" onChange={(e) => { changeRegion(e, 5) }}>
        <div className="info">
          <div>卸货时间:</div>
          <input ref={time2} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <div className="money">
        <div className="title">订金</div>
        <input type="number" ref={deposit} placeholder="20-200元" />
        <div className={select === 0 ? "btn select" : "btn"} onClick={() => { setSelect(0) }}> 不退还</div>
        <div className={select === 1 ? "btn select" : "btn"} onClick={() => { setSelect(1) }}>退还</div>
      </div>
      <div className="price">
        <div className="title">一口价</div>
        <input type="number" ref={freight} placeholder="99-99999元" />
        <div className="estimate" onClick={estimate}>估价</div>
      </div>
      <div className="person">
        <div className="title">装货联系人</div>
        <input type="number" ref={loadingContactor} maxLength={11} placeholder="必填" />
      </div>
      <div className="person">
        <div className="title">卸货联系人</div>
        <input type="number" ref={unloadingContactor} maxLength={11} placeholder="必填" />
      </div>
      <div className="remarks">
        <div className="title">备注</div>
        <textarea ref={remark} placeholder="该项可不填" />
      </div>
      <div className="auto" onClick={() => { setCheck(!check) }}>
        {check ? <img src={checked} alt="" /> : <img src={uncheck} alt="" />}
        {' '}我已阅读并同意<i>《货物运输协议》</i>
      </div>
      <div className="submit" onClick={submit}>确认变更</div>

      <TagListPick
        title="车长车型"
        visible={tagListPickVisible}
        tagListObj={tagListObj}
        cancleCallback={() => { setTagListPickVisible(false) }}
        confirmCallback={handleTagListPickConfirm}
      />

      <AtModal isOpened={isShow} closeOnClickOverlay={false}>
        <AtModalHeader>重量/体积</AtModalHeader>
        <AtModalContent>
          <div className="size">
            <div>重量</div>
            <input ref={weight} type="number" />
            <div>吨</div>
          </div>
          <div className="size">
            <div>体积</div>
            <input ref={volume} type="number" />
            <div>立方米</div>
          </div>
        </AtModalContent>
        <AtModalAction> <Button onClick={() => { setIsShow(false) }}>取消</Button> <Button onClick={() => { showInfo() }}>确定</Button> </AtModalAction>
      </AtModal>

    </div >
  )
}

export default Edit